package com.fanshilz.flower2025.apps.admin.project.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.fanshilz.flower2025.apps.admin.project.req.*;
import com.fanshilz.flower2025.apps.admin.project.resp.AttachmetnUploadResp;
import com.fanshilz.flower2025.apps.admin.project.resp.CoverImageTableDetailResp;
import com.fanshilz.flower2025.apps.admin.project.resp.ProjectRecordDetailResp;
import com.fanshilz.flower2025.apps.admin.project.resp.ProjectTableDetailResp;
import com.fanshilz.flower2025.apps.admin.satoken.AdminCurrentUser;
import com.fanshilz.flower2025.apps.admin.satoken.StpAdminUtil;
import com.fanshilz.flower2025.business.flower.attachment.entity.Attachment;
import com.fanshilz.flower2025.business.flower.attachment.entity.AttachmentObjTypeEnum;
import com.fanshilz.flower2025.business.flower.attachment.entity.ProjectCoverImage;
import com.fanshilz.flower2025.business.flower.attachment.service.IAttachmentService;
import com.fanshilz.flower2025.business.flower.project.entity.CreateUserTypeEnum;
import com.fanshilz.flower2025.business.flower.project.entity.Project;
import com.fanshilz.flower2025.business.flower.project.entity.ProjectStatusEnum;
import com.fanshilz.flower2025.business.flower.project.service.IProjectService;
import com.fanshilz.flower2025.business.flower.projectRecord.entity.ProjectRecord;
import com.fanshilz.flower2025.business.flower.projectRecord.service.IProjectRecordService;
import com.fanshilz.flower2025.framework.aliyun.sms.AliyunSmsUtil;
import com.fanshilz.flower2025.framework.resp.Resp;
import com.fanshilz.flower2025.framework.resp.TableResp;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.github.linpeilie.Converter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;

import static com.fanshilz.flower2025.business.flower.attachment.entity.table.AttachmentTableDef.ATTACHMENT;
import static com.fanshilz.flower2025.business.flower.project.entity.table.ProjectTableDef.PROJECT;
import static com.fanshilz.flower2025.business.flower.projectRecord.entity.table.ProjectRecordTableDef.PROJECT_RECORD;

@Slf4j
@RestController
@RequestMapping("/admin/project")
public class ProjectController {

    @Resource
    private IProjectService projectService;
    @Resource
    private IAttachmentService attachmentService;
    @Resource
    private Converter converter;
    @Resource
    private IProjectRecordService projectRecordService;

    @PostMapping("/selectCoverImage")
    @Transactional
    public Resp<Void> selectCoverImage(@RequestBody @Valid SelectCoverImageReq req) {
        Attachment att = attachmentService.getById(req.getFileId());
        attachmentService.save(Attachment.builder()
                .filePath(att.getFilePath())
                .objType(AttachmentObjTypeEnum.projectIndexCover.getValue())
                .objId(req.getProjectId())
                .fileSuffix(att.getFileSuffix())
                .fileSize(att.getFileSize())
                .originalFileName(att.getOriginalFileName())
                .fileType(att.getFileType())
                .build());
        attachmentService.save(Attachment.builder()
                .filePath(att.getFilePath())
                .objType(AttachmentObjTypeEnum.projectDetailCover.getValue())
                .objId(req.getProjectId())
                .fileSuffix(att.getFileSuffix())
                .fileSize(att.getFileSize())
                .originalFileName(att.getOriginalFileName())
                .fileType(att.getFileType())
                .build());
        return Resp.success();
    }

    @PostMapping("/projectRecords")
    public Resp<List<ProjectRecordDetailResp>> projectRecords(@RequestBody @Valid ProjectRecordsReq req) {
        QueryWrapper qw = QueryWrapper.create()
                .where(PROJECT_RECORD.PROJECT_ID.eq(req.getProjectId()))
                .orderBy(PROJECT_RECORD.RECORD_ID.desc());
        List<ProjectRecordDetailResp> resp = projectRecordService.getMapper()
                .selectListWithRelationsByQueryAs(qw, ProjectRecordDetailResp.class);
        return Resp.success(resp);
    }

    @PostMapping("/saveProjectRecord")
    public Resp<AttachmetnUploadResp> saveProjectRecord(@RequestBody @Valid ProjectRecordSaveReq req) {
        ProjectRecord pr = converter.convert(req, ProjectRecord.class);
        pr.setCreateUserType(CreateUserTypeEnum.SYS_USER);
        projectRecordService.save(pr);
        return Resp.success(new AttachmetnUploadResp(pr.getRecordId(), null, AttachmentObjTypeEnum.projectRecord.getValue(), AttachmentObjTypeEnum.projectRecord.getLable()));
    }

    @PostMapping("/delist")
    public Resp<Void> delist(@RequestBody @Valid ProjectDelistReq req) {

        projectService.updateById(Project.builder()
                .projectId(req.getProjectId())
                .projectStatusValue(ProjectStatusEnum.DELIST.getValue())
                .projectStatusLabel(ProjectStatusEnum.DELIST.getLable())
                .build());

        Project one = projectService.getOne(QueryWrapper.create()
                .select(PROJECT.PROJECT_USER_MOBILE)
                .where(PROJECT.PROJECT_ID.eq(req.getProjectId())));

        // 下架
        if (ObjUtil.isNotNull(one) && StrUtil.isNotBlank(one.getProjectUserMobile())) {
            AliyunSmsUtil.sendTemplateCode("SMS_478930674", one.getProjectUserMobile());
        }

        return Resp.success();
    }

    @PostMapping("/putaway")
    public Resp<Void> putaway(@RequestBody @Valid ProjectPutawayReq req) {
        AdminCurrentUser currentUser = StpAdminUtil.currentUser();
        projectService.updateById(Project.builder()
                .projectId(req.getProjectId())
                .projectStatusValue(ProjectStatusEnum.PUTAWAY.getValue())
                .projectStatusLabel(ProjectStatusEnum.PUTAWAY.getLable())
                .projectPublishTime(new Timestamp(System.currentTimeMillis()))
                .projectPublishUserName(currentUser.getNickName())
                .projectPublishUserId(currentUser.getUserId())
                .build());

        Project one = projectService.getOne(QueryWrapper.create()
                .select(PROJECT.PROJECT_USER_MOBILE)
                .where(PROJECT.PROJECT_ID.eq(req.getProjectId())));

        // 上架
        if (ObjUtil.isNotNull(one) && StrUtil.isNotBlank(one.getProjectUserMobile())) {
            AliyunSmsUtil.sendTemplateCode("SMS_479050685", one.getProjectUserMobile());
        }
        return Resp.success();
    }

    @PostMapping("/remove/{projectId}")
    public Resp<Void> remove(@PathVariable Long projectId) {
        projectService.updateById(Project.builder()
                .projectId(projectId)
                .delFlag(true)
                .build());
        return Resp.success();
    }

    @PostMapping("/saveOrUpdate")
    @Transactional
    public Resp<Void> saveOrUpdate(@RequestBody @Valid ProjectSaveOrUpdateReq req) {
        Project p = converter.convert(req, Project.class);
        if (ObjUtil.isNull(p.getProjectId())) {
            p.setProjectUuid("1" + RandomUtil.randomNumbers(7));
            p.setProjectStatusValue(ProjectStatusEnum.PUTAWAY.getValue());
            p.setProjectStatusLabel(ProjectStatusEnum.PUTAWAY.getLable());
            p.setCreateUserType(CreateUserTypeEnum.SYS_USER.getValue());

            AdminCurrentUser currentUser = StpAdminUtil.currentUser();

            p.setProjectPublishTime(new Timestamp(System.currentTimeMillis()));
            p.setProjectPublishUserId(currentUser.getUserId());
            p.setProjectPublishUserName(currentUser.getNickName());

            if (StrUtil.isBlank(p.getProjectUserMobile())) {
                p.setProjectUserMobile(currentUser.getUserMobile());
                p.setProjectUserName(currentUser.getNickName());
            }

//            String image = ProjectCoverImage.randomImageCover();

            // 随机选择封面图
//            attachmentService.save(Attachment.builder()
//                    .objId(p.getProjectId())
//                    .objType(AttachmentObjTypeEnum.projectIndexCover.getValue())
//                    .filePath(image)
//                    .build());

            // 详情封面图
//            attachmentService.save(Attachment.builder()
//                    .objId(p.getProjectId())
//                    .objType(AttachmentObjTypeEnum.projectDetailCover.getValue())
//                    .filePath(image)
//                    .build());
        }

        projectService.saveOrUpdate(p);
        return Resp.success();
    }

    @PostMapping("/table")
    public Resp<TableResp<ProjectTableDetailResp>> table(@RequestBody @Valid ProjectTableReq req) {
        QueryWrapper qw = QueryWrapper.create()
                .where(PROJECT.PROJECT_ID.eq(req.getProjectId()))
                .where(PROJECT.PROJECT_UUID.eq(req.getProjectUuid()).when(StrUtil.isNotBlank(req.getProjectUuid())))
                .where(PROJECT.PROJECT_NAME.eq(req.getProjectName()).when(StrUtil.isNotBlank(req.getProjectName())))
                .where(PROJECT.PROJECT_SHORT_NAME.eq(req.getProjectShortName()).when(StrUtil.isNotBlank(req.getProjectShortName())));
        qw.orderBy(PROJECT.PROJECT_ID.desc());
        Page<ProjectTableDetailResp> page = projectService.getMapper()
                .paginateWithRelationsAs(Page.of(req.getCurrent(), req.getPageSize(), req.getTotal()), qw, ProjectTableDetailResp.class);
        return Resp.success(new TableResp<>(page.getRecords(), page.getTotalRow()));
    }

    @PostMapping("/coverImageTable")
    public Resp<TableResp<CoverImageTableDetailResp>> table(@RequestBody @Valid CoverImageTableReq req) {
        QueryWrapper qw = QueryWrapper.create()
                .where(ATTACHMENT.OBJ_TYPE.eq(AttachmentObjTypeEnum.projectCover.getValue()));

        Page<CoverImageTableDetailResp> page = attachmentService.getMapper()
                .paginateWithRelationsAs(Page.of(req.getCurrent(), req.getPageSize(), req.getTotal()), qw, CoverImageTableDetailResp.class);
        return Resp.success(new TableResp<>(page.getRecords(), page.getTotalRow()));
    }


}
